package com.photoeditor.demo.ui.widget.image.compose;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.bean.EditTextBean;
import com.photoeditor.demo.model.bean.stash.TextBean;
import com.photoeditor.demo.model.event.ExitAddTextFuntionEvent;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.widget.image.attacher.CanvasPhotoViewAttacher;
import com.photoeditor.demo.ui.widget.image.attacher.IPhotoView;
import com.photoeditor.demo.util.TouchUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;


/**
 * 这个类用于在图片上添加文字和合成文字
 * adjustUnspecified|stateHidden
 */
public class CanvasEditTextView extends AppCompatImageView implements IPhotoView {

    //原来的Bitmap
    private Bitmap mSrcBitmap;

    //用于标识是否初始化
    private boolean mIsInit = false;

    //用于存储EditText的Bound Rect
    private LinkedList<TextBean> mBeans;

    //当前选中的下标
    private int mSelectIndex = -1;

    //本界面的Bound Rect
    private RectF mRect;

    //Drawable的Bound Rect  默认
    private RectF mDrawableRect;

    //用于绘制TextRect
    private Paint mPaint;

    //用于绘制ViewRect
    private Paint mLinePaint;

    //用于绘制ButtonRect
    private Paint mButtonPaint;

    //回调
    private ICanvasEditListener mListener;

    //点击回调
    private IClickEditTextListener mClickListener;

    //默认的字符串
    private String mDefaultString;

    //操作Drawable
    private Drawable mOperationDrawable;

    private Drawable mDeleteDrawable;

    private final CanvasPhotoViewAttacher mAttacher;

    private Matrix mCacheMatrix;

    private boolean mNeedNotScale = true;

    private boolean mIsNeedAddText = false;

    private Paint mBitmapPaint;

    private boolean mIsMove = false;

    /**
     * 保存使用过得字体，用于保存图片时统计
     **/
    private ArrayList<String> mUsedFontKey = new ArrayList<>();

    private CanvasPhotoViewAttacher.OnMatrixChangedListener mMatrixChangeListener = new CanvasPhotoViewAttacher.OnMatrixChangedListener() {
        @Override
        public void onMatrixChanged(RectF rect) {
            if (mDrawableRect == null) {
                mDrawableRect = new RectF();
            }
            mDrawableRect.set(rect);
            if (mIsInit) {
                mDrawableRect.offset(mRect.left, mRect.top);
                countScaleAndDo();
            }
            refresh();
        }
    };
    private boolean mIsClickDelete;
    private RectF mCacheRect = new RectF();

    public CanvasEditTextView(Context context) {
        this(context, null);
    }

    public CanvasEditTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CanvasEditTextView(Context context, AttributeSet attrs,
                              int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        super.setScaleType(ScaleType.MATRIX);
        mAttacher = new CanvasPhotoViewAttacher(this);
        setOnMatrixChangeListener(mMatrixChangeListener);
        initialize();
    }

    private void initialize() {
        setWillNotDraw(false);
        if (isHardwareAccelerated()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        mDefaultString = getResources().getString(R.string.default_string);
        mOperationDrawable = getResources().getDrawable(R.drawable.ic_rotate);
        mDeleteDrawable = getResources().getDrawable(R.drawable.ic_close_emoji);
        mCacheMatrix = new Matrix();
        setMaximumScale(8.0f);
        setMediumScale(1.0f);

        int i = DeviceUtils.dip2px(getContext(), 1);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(getResources().getColor(R.color.image_edit_text_bound_color));
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(i);
        mPaint.setStyle(Style.STROKE);
        mBeans = new LinkedList<>();
        mSelectIndex = -1;

        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //PathEffect effect = new DashPathEffect(new float[]{8, 8}, 1);
        mLinePaint.setAntiAlias(true);
        mLinePaint.setColor(getResources().getColor(R.color.image_edit_text_line_color));
        //mLinePaint.setPathEffect(effect);
        mLinePaint.setStyle(Style.STROKE);
        mLinePaint.setStrokeWidth(i);

        mButtonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //			mButtonPaint.setColor(Color.RED);
        mButtonPaint.setAntiAlias(true);
        //			mButtonPaint.setStyle(Style.FILL);
        //			mButtonPaint.setStrokeWidth(i);

        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setFilterBitmap(true);

    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        if (mSrcBitmap == null || mSrcBitmap != bm) {
            mIsInit = false;
        }
        mSrcBitmap = bm;
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        if (drawable instanceof BitmapDrawable) {
            Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
            if (mSrcBitmap == null || mSrcBitmap != bm) {
                mIsInit = false;
            }
            mSrcBitmap = bm;
            if (null != mAttacher) {
                mAttacher.update();
            }
        }
    }

    /**
     * 用于获取合成好的图片
     *
     * @return
     */
    public Bitmap getDstBitmap() {
        if (mSrcBitmap != null && !mSrcBitmap.isRecycled()) {
            Matrix matrix1 = this.getImageMatrix();
            float[] values1 = new float[10];
            matrix1.getValues(values1);

            Bitmap bitmap = Bitmap.createBitmap(mSrcBitmap.getWidth(), mSrcBitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
            p.setAntiAlias(true);
            p.setFilterBitmap(true);

            canvas.drawBitmap(mSrcBitmap, 0, 0, p);
            RectF cacheRect = new RectF();
            for (int i = 0; i < mBeans.size(); i++) {
                TextBean bean = mBeans.get(i);
                if (bean.isNeedSave()) {
                    RectF tr = bean.getRect();
                    cacheRect.left = tr.left - mDrawableRect.left;
                    cacheRect.top = tr.top - mDrawableRect.top;
                    cacheRect.right = tr.right - mDrawableRect.left;
                    cacheRect.bottom = tr.bottom - mDrawableRect.top;
                    canvas.save();
                    canvas.scale(1 / values1[0], 1 / values1[4]);
                    canvas.rotate(bean.getDegree(), cacheRect.centerX(), cacheRect.centerY());
                    //canvas.drawRoundRect(new RectF(tr.left - mDrawableRect.left, tr.top - mDrawableRect.top, tr.right - mDrawableRect.left, tr.bottom - mDrawableRect.top), tr.height() / 10, tr.height() / 10, bean.getBgPaint());
                    //canvas.translate(tr.left - mDrawableRect.left + bean.getPadding(), tr.top - mDrawableRect.top + bean.getPadding());
                    canvas.drawBitmap(bean.getBitmap(), null, cacheRect, p);
                    canvas.restore();
                    mUsedFontKey.add(bean.getFontKey());
                }
            }

            /*for (int i = 0; i < mBeans.size(); i++) {
                TextBean bean = mBeans.get(i);
                if (bean.isNeedSave()) {
                    RectF tr = bean.getRect();
                    Matrix m = new Matrix();
                    m.setRotate(bean.getDegree(), tr.centerX(), tr.centerY());
                    float[] dst1 = new float[2];
                    float[] dst2 = new float[2];
                    m.mapPoints(dst1, new float[]{tr.left, tr.top});
                    m.mapPoints(dst2, new float[]{tr.right, tr.bottom});
                    if (!mDrawableRect.contains(dst1[0], dst1[1]) && !mDrawableRect.contains(dst2[0], dst2[1])) {
                    } else {
                        RectF tr1 = new RectF(mDrawableRect.left, mDrawableRect.top, mDrawableRect.left + mDrawableRect.width() / 3, mDrawableRect.top + mDrawableRect.height() / 3);
                        RectF tr2 = new RectF(tr1.right, tr1.top, tr1.right + mDrawableRect.width() / 3, tr1.bottom);
                        RectF tr3 = new RectF(tr2.right, tr1.top, mDrawableRect.right, tr1.bottom);

                        RectF tr4 = new RectF(tr1.left, tr1.bottom, tr1.right, tr1.bottom + mDrawableRect.height() / 3);
                        RectF tr5 = new RectF(tr2.left, tr4.top, tr2.right, tr4.bottom);
                        RectF tr6 = new RectF(tr3.left, tr4.top, tr3.right, tr4.bottom);

                        RectF tr7 = new RectF(tr4.left, tr4.bottom, tr4.right, tr4.bottom + mDrawableRect.height() / 3);
                        RectF tr8 = new RectF(tr5.left, tr7.top, tr5.right, tr7.bottom);
                        RectF tr9 = new RectF(tr6.left, tr7.top, tr6.right, tr7.bottom);

                        int a = 0, b = 0;

                        if (mDrawableRect.contains(dst1[0], dst1[1])) {
                            if (tr1.contains(dst1[0], dst1[1])) {
                                a = 1;
                            } else if (tr2.contains(dst1[0], dst1[1])) {
                                a = 2;
                            } else if (tr3.contains(dst1[0], dst1[1])) {
                                a = 3;
                            } else if (tr4.contains(dst1[0], dst1[1])) {
                                a = 4;
                            } else if (tr5.contains(dst1[0], dst1[1])) {
                                a = 5;
                            } else if (tr6.contains(dst1[0], dst1[1])) {
                                a = 6;
                            } else if (tr7.contains(dst1[0], dst1[1])) {
                                a = 7;
                            } else if (tr8.contains(dst1[0], dst1[1])) {
                                a = 8;
                            } else if (tr9.contains(dst1[0], dst1[1])) {
                                a = 9;
                            }
                        }

                        if (mDrawableRect.contains(dst2[0], dst2[1])) {
                            if (tr1.contains(dst2[0], dst2[1])) {
                                b = 1;
                            } else if (tr2.contains(dst2[0], dst2[1])) {
                                b = 2;
                            } else if (tr3.contains(dst2[0], dst2[1])) {
                                b = 3;
                            } else if (tr4.contains(dst2[0], dst2[1])) {
                                b = 4;
                            } else if (tr5.contains(dst2[0], dst2[1])) {
                                b = 5;
                            } else if (tr6.contains(dst2[0], dst2[1])) {
                                b = 6;
                            } else if (tr7.contains(dst2[0], dst2[1])) {
                                b = 7;
                            } else if (tr8.contains(dst2[0], dst2[1])) {
                                b = 8;
                            } else if (tr9.contains(dst2[0], dst2[1])) {
                                b = 9;
                            }
                        }
                    }

                    float sp = DeviceUtils.dip2px(getContext(), bean.getPaint().getTextSize());

                    int data = 4;
                    if (sp < 10f) {
                        data = 1;
                    } else if (sp >= 10f && sp < 15f) {
                        data = 2;
                    } else if (sp >= 15f && sp < 20f) {
                        data = 3;
                    } else if (sp >= 20f && sp < 25f) {
                        data = 4;
                    } else if (sp >= 25f && sp < 30f) {
                        data = 5;
                    } else if (sp >= 30f && sp < 35f) {
                        data = 6;
                    } else if (sp >= 35f && sp < 40f) {
                        data = 7;
                    } else if (sp >= 40f) {
                        data = 8;
                    }

                }
            }*/
            return bitmap;
        }

        return mSrcBitmap;
    }

    /**
     * 重写onDraw
     */
    @Override
    protected void onDraw(Canvas canvas) {
        if (mSrcBitmap == null || mSrcBitmap.isRecycled()) {
            return;
        }
        super.onDraw(canvas);
        for (int i = 0; i < mBeans.size(); i++) {
            if (i != mSelectIndex) {
                TextBean bean = mBeans.get(i);
                RectF tr = bean.getRect();
                mCacheRect.left = tr.left - mRect.left;
                mCacheRect.top = tr.top - mRect.top;
                mCacheRect.right = tr.right - mRect.left;
                mCacheRect.bottom = tr.bottom - mRect.top;
                int count1 = canvas.save();
                if (!bean.isTouch()) {
                    canvas.clipRect(mDrawableRect.left - mRect.left, mDrawableRect.top - mRect.top, mDrawableRect.right - mRect.left, mDrawableRect.bottom - mRect.top);
                }
                int count2 = canvas.save();
                canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());

                //canvas.drawRoundRect(new RectF(tr.left - mRect.left, tr.top - mRect.top, tr.right - mRect.left, tr.bottom - mRect.top), tr.height() / 10, tr.height() / 10, bean.getBgPaint());

                //canvas.translate(tr.left - mRect.left + bean.getPadding(), tr.top - mRect.top + bean.getPadding());
                canvas.drawBitmap(bean.getBitmap(), null, mCacheRect, mBitmapPaint);
                canvas.restoreToCount(count2);
                canvas.restoreToCount(count1);
            }
        }

        if (mSelectIndex < mBeans.size() && mSelectIndex >= 0) {
            TextBean bean = mBeans.get(mSelectIndex);
            RectF tr = bean.getRect();
            RectF vr = tr;
            RectF br = bean.getButtonRect();
            RectF dr = bean.getDeleteRect();
            mCacheRect.left = tr.left - mRect.left;
            mCacheRect.top = tr.top - mRect.top;
            mCacheRect.right = tr.right - mRect.left;
            mCacheRect.bottom = tr.bottom - mRect.top;
            mOperationDrawable.setBounds((int) (br.left - mRect.left + 0.5f), (int) (br.top - mRect.top + 0.5f), (int) (br.right - mRect.left + 0.5f), (int) (br.bottom - mRect.top + 0.5f));
            //if (tr.equals(vr)) {//相同的Rect

            if (!bean.isTouch()) {
                canvas.clipRect(mDrawableRect.left - mRect.left, mDrawableRect.top - mRect.top, mDrawableRect.right - mRect.left, mDrawableRect.bottom - mRect.top);
            }

            int count3 = canvas.save();
            canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
            //canvas.translate(tr.left - mRect.left + bean.getPadding(), tr.top - mRect.top + bean.getPadding());
            canvas.drawBitmap(bean.getBitmap(), null, mCacheRect, mBitmapPaint);
            canvas.restoreToCount(count3);

            int count4 = canvas.save();
            canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
            canvas.drawRect(mCacheRect, mLinePaint);
//				canvas.drawRect(tr.left - mRect.left, tr.top - mRect.top, tr.right - mRect.left, tr.bottom - mRect.top, mPaint);
//				canvas.drawCircle(vr.right - mRect.left, vr.top - mRect.top, EditTextBean.RADIUS * 2, mButtonPaint);
            //canvas.drawRoundRect(new RectF(tr.left - mRect.left, tr.top - mRect.top, tr.right - mRect.left, tr.bottom - mRect.top), tr.height() / 10, tr.height() / 10, bean.getBgPaint());

            if (mMode != MODE_SCALE_OR_ROTATION_OR_MOVE) {
                mOperationDrawable.draw(canvas);
            }
            if (mMode != MODE_SCALE_OR_ROTATION && mMode != MODE_SCALE_OR_ROTATION_OR_MOVE) {
                mDeleteDrawable.setBounds((int) (dr.left - mRect.left + 0.5f), (int) (dr.top - mRect.top + 0.5f), (int) (dr.right - mRect.left + 0.5f), (int) (dr.bottom - mRect.top + 0.5f));
                mDeleteDrawable.draw(canvas);
            }
            canvas.restoreToCount(count4);

            /*} else {

                if (!bean.isTouch()) {
                    canvas.clipRect(mDrawableRect.left - mRect.left, mDrawableRect.top - mRect.top, mDrawableRect.right - mRect.left, mDrawableRect.bottom - mRect.top);
                }

                int count5 = canvas.save();
                canvas.rotate(bean.getmDegree(), (tr.left - mRect.left + tr.right - mRect.left) / 2, (tr.top - mRect.top + tr.bottom - mRect.top) / 2);
                canvas.drawRect(vr.left - mRect.left, vr.top - mRect.top, vr.right - mRect.left, vr.bottom - mRect.top, mLinePaint);
//				canvas.drawRect(tr.left - mRect.left, tr.top - mRect.top, tr.right - mRect.left, tr.bottom - mRect.top, mPaint);
//				canvas.drawCircle(vr.right - mRect.left, vr.top - mRect.top, EditTextBean.RADIUS * 2, mButtonPaint);
                canvas.drawRoundRect(new RectF(tr.left - mRect.left, tr.top - mRect.top, tr.right - mRect.left, tr.bottom - mRect.top), tr.height() / 10, tr.height() / 10, bean.getBgPaint());
                mOperationDrawable.draw(canvas);
                canvas.restoreToCount(count5);

                int count6 = canvas.save();
                canvas.rotate(bean.getmDegree(), (tr.left - mRect.left + tr.right - mRect.left) / 2, (tr.top - mRect.top + tr.bottom - mRect.top) / 2);
                canvas.translate(tr.left - mRect.left + bean.getPadding(), tr.top - mRect.top + bean.getPadding());
                bean.getmLayout().draw(canvas);
                canvas.restoreToCount(count6);
            }*/

        }
    }

    /**
     * 初始化这个类   这个方法在使用前必须调用 ！！！！！
     *
     * @param rect 整个View的Rect
     */
    public void init(RectF rect) {

        mRect = rect;
        countDrawableInitPosition(rect);
        mBaseDrawableRect = new RectF(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());

//			mDrawableRect = dRect;
        if (mDrawableRect != null) {
            mDrawableRect.offset(mRect.left, mRect.top);
        }

        mIsInit = true;
        this.addText(mDefaultString);
        /* else if(!mRect.equals(rect) || !mDrawableRect.equals(dRect)){
            mRect = rect;
			mDrawableRect = dRect;
			removeSelectText();
			this.addText(mDefaultString, mDefaultTp);
		}*/
    }

    /**
     * 设置当前的选中并刷新界面
     *
     * @param index
     */
    public void setSelectIndex(int index) {
        int length = mBeans.size();
        if (index < length && index >= 0) {
            clearUnAbleText();
            TextBean bean = mBeans.get(index);
            mBeans.remove(index);
            mBeans.addLast(bean);
            mSelectIndex = (length - 1);
            refresh();
            if (mListener != null) {
                mListener.onSelected();
            }
        }
    }

    /**
     * 添加文字区域
     *
     * @param e
     */
    public void addText(String e) {
        addText(e, true);
    }

    public void addText(String e, boolean notify) {
        //默认CENTER
        TextBean bean = new TextBean(e, mSupportDrawableRect.centerX(), mSupportDrawableRect.bottom - DeviceUtils.dip2px(ComponentContext.getContext(), 50));
//		bean.setLastMatrix(getImageMatrix()); 这句话不能增加的原因是  这个方法调用时View还未初始化完成  会导致错误
        clearUnAbleText();
        mBeans.add(bean);
        mSelectIndex = mBeans.size() - 1;
        refresh();
        if (mListener != null && notify) {
            mListener.onSelected();
        }
    }

    /**
     * 添加文字区域
     *
     * @param e
     * @param pointX
     * @param pointY
     */
    public void addText(String e, float pointX, float pointY) {
        TextBean bean = new TextBean(e, pointX, pointY);
        bean.setLastMatrix(getImageMatrix());
//        clearUnAbleText();
        mBeans.add(bean);
        mSelectIndex = mBeans.size() - 1;
        if (mListener != null) {
            mListener.onSelected();
        }
    }

    public void deleteText(int position) {
        if (position < mBeans.size() && position >= 0) {
            mBeans.remove(position);
            mSelectIndex = -1;
            refresh();
            if (mListener != null) {
                mListener.onDelete(null);
            }
            //删除完所有文字后退出当前功能
            if (mBeans.size() == 0) {
                EventBus.getDefault().post(new ExitAddTextFuntionEvent());
            }
        }
    }

    /**
     * addText 的时候使用他
     */
    private void clearUnAbleText() {
        int len = mBeans.size();
        for (int i = 0; i < len; ) {
            if (!mBeans.get(i).isNeedSave()) {
                mBeans.remove(i);
                len -= 1;
            } else {
                i++;
            }
        }
    }

    /**
     * 更新文字Bold
     *
     * @param isBold
     */
    public void updateBold(boolean isBold) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {

            TextBean bean = mBeans.get(mSelectIndex);
            bean.updateBold(isBold);
            refresh();
        }
    }

    /**
     * 更新文字阴影
     *
     * @param isShader
     */
    public void updateShadow(boolean isShader) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {

            TextBean bean = mBeans.get(mSelectIndex);
            bean.updateShadow(isShader);
            refresh();
        }
    }

    /**
     * 更新文字颜色
     *
     * @param color
     */
    public void updateColor(int color) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {

            TextBean bean = mBeans.get(mSelectIndex);
            bean.updateColor(color);
            refresh();
        }
    }

    public void updateColor(int textColor, int bgColor, int checkId, int style) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {

            TextBean bean = mBeans.get(mSelectIndex);
            bean.updateColor(textColor, bgColor);
            bean.updateCheckId(checkId);
            bean.updateStyle(style);
            refresh();
        }
    }

    public void updateFont(Typeface typeface, String fontKey) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
            TextBean bean = mBeans.get(mSelectIndex);
            bean.updateFont(typeface, fontKey);
            refresh();
        }
    }

    /**
     * 更新文字
     *
     * @param str
     */
    public void updateText(String str) {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {

            TextBean bean = mBeans.get(mSelectIndex);
            if (TextUtils.isEmpty(str.trim())) {
                bean.updateString(mDefaultString);
                bean.setIsNeedSave(false);
                if (mListener != null) {
                    mListener.onNeedSaveChangedTo(isNeedSave());
                }
            } else {
                bean.updateString(str);
                bean.setIsNeedSave(true);
                if (mListener != null) {
                    mListener.onNeedSaveChangedTo(true);
                }
            }
            refresh();
        }
    }

    /**
     * 获取当前选中Bean的 bold状态
     *
     * @return
     */
    public boolean getSelectBeanIsBold() {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
            TextBean bean = mBeans.get(mSelectIndex);
            return bean.isBold();
        }
        return false;
    }

    /**
     * 获取当前选中Bean的 shadow状态
     *
     * @return
     */
    public boolean getSelectBeanIsShadow() {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
            TextBean bean = mBeans.get(mSelectIndex);
            return bean.isShadow();
        }
        return false;
    }

    /**
     * 获取当前选中Bean的 Color
     *
     * @return
     */
    public int getSelectBeanColor() {
        if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
            TextBean bean = mBeans.get(mSelectIndex);
            return bean.getColor();
        }
        return Color.WHITE;
    }

//	/**
//	 * 移除某个文字显示区域
//	 */
//	public void removeSelectText(){
//		if(mSelectIndex >= 0 && mSelectIndex < mBeans.size()){
//			mBeans.remove(mSelectIndex);
//			mSelectIndex = - 1;
//			mHandler.removeMessages(DO_ON_DRAW);
//			mHandler.sendEmptyMessage(DO_ON_DRAW);
//			if(mListener != null){
//				mListener.onNeedSaveChangedTo(isNeedSave());
//			}
//		}
//	}

    /**
     * 清除所有的
     */
    public void reset() {
        if (mIsInit) {
            mBeans.clear();
            mSelectIndex = -1;
            this.addText(mDefaultString, false);
            if (mListener != null) {
                mListener.onNeedSaveChangedTo(false);
            }
            if (null != mAttacher) {
                mAttacher.update();
            }
        }
    }

    /**
     * 是否需要保存
     *
     * @return
     */
    public boolean isNeedSave() {
        int length = mBeans.size();
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                TextBean bean = mBeans.get(i);
                if (bean.isNeedSave()) {
                    return true;
                }
            }
        }
        return false;
    }

    public void setListener(ICanvasEditListener listener) {
        mListener = listener;
    }

    public void setOnEditTextClickListener(IClickEditTextListener listener) {
        mClickListener = listener;
    }

    /**
     * 获取当前显示图片的宽高
     *
     * @return
     */
    public float[] getCurrentSize() {
        float result[] = new float[]{0.0f, 0.0f};
        Drawable mDrawable = this.getDrawable();
        if (mDrawable == null) {
            return result;
        }
        Rect r = mDrawable.getBounds();
        //真实宽高
        int w = r.width();
        int h = r.height();
        Matrix matrix1 = this.getImageMatrix();
        float[] values1 = new float[10];
        matrix1.getValues(values1);
        //当前显示的宽高

        result[0] = w * values1[0];
        result[1] = h * values1[4];
        return result;
    }

    /**
     * 获取当前图片显示的Bounds
     *
     * @return Rect
     */
    public RectF getDrawableRect() {
        float size[] = getCurrentSize();
        float viewWidth = this.getWidth();
        float Viewheight = this.getHeight();

        int bLeft, bTop;
        int vLeft, vTop;
        int location[] = new int[2];
        this.getLocationInWindow(location);
        vLeft = location[0];
        vTop = location[1];

        float widthDistance, heightDistance;
        widthDistance = (viewWidth - size[0]) / 2;
        heightDistance = (Viewheight - size[1]) / 2;
        bLeft = (int) (vLeft + widthDistance + 0.5);
        bTop = (int) (vTop + heightDistance + 0.5);

        return new RectF(bLeft, bTop, (int) (bLeft + size[0] + 0.5f), (int) (bTop + size[1] + 0.5f));
    }

    /**
     * 获取当前View显示的Bounds
     *
     * @return
     */
    public RectF getViewRect() {
        return new RectF(0, 0, this.getWidth(), this.getHeight());
    }


    /**
     * 以下是onTouchEvent的相关代码
     */


    //touch down 的坐标
    private float mDownX;
    private float mDownY;

    /*各种移动的模式*/
    private int mMode;

    /*点击*/
    private boolean mIsClick = false;

    //当前已经选中直接移动
    public static final int MODE_MOVE = 1;

    //当前已经选中直接旋转或者缩放
    public static final int MODE_SCALE_OR_ROTATION = 2;

    //当前未选中  需要先选中让后再移动
    public static final int MODE_SELECT_MOVE = 3;

    //当前未选中  需要先选中让后再移动
    public static final int MODE_NEW_TEXT = 4;

    //未选中
    public static final int MODE_SELECT_NONE = 5;

    public static final int MODE_SCALE_OR_ROTATION_OR_MOVE = 6;

    //无操作
    public static final int MODE_NONE = -1;

    //用于缩小到很小时然后再放大的标识
    private boolean mType = false;

    //用于更新视图
    public static final int DO_ON_DRAW = 0x101;

    //用于更新视图
    public static final int ADD_NEW_TEXT = 0x102;

    //当前选中的EditTextBean
    private TextBean mCurrentTouchBean;

    /**
     * 处理更新
     */
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == DO_ON_DRAW) {
                postInvalidate();
            } else if (msg.what == ADD_NEW_TEXT) {

            }
        }

        ;
    };

    /**
     * 用于获取当前选中的对象
     * x y是点击的真实坐标
     *
     * @param x
     * @param y
     * @return
     */
    private int getTouchEditTextBeanIndex(float x, float y) {
        if (mBeans != null) {
            int length = mBeans.size();
            for (int i = length - 1; i >= 0; i--) {
                TextBean bean = mBeans.get(i);
                //dst用于存储变换后的点
                float[] dst = new float[2];
                bean.getMatrix().mapPoints(dst, new float[]{x, y});
                RectF vr = bean.getRect();
                if (vr.contains(dst[0], dst[1])) {
                    //把将要选中的放到最后  绘制的时候就会正确
                    mBeans.remove(i);
                    mBeans.addLast(bean);
                    return (length - 1);
                }
            }
        }
        return -1;
    }

    float oldDist = 1f;
    float oldRotation = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mIsInit) return super.onTouchEvent(event);
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                oldRotation = rotation(event);
                int pos = getTouchEditTextBeanIndex(event.getX(0), event.getY(0));
                if (pos != -1) {
                    mMode = MODE_SCALE_OR_ROTATION_OR_MOVE;
                    mIsClick = true;
                    mSelectIndex = pos;
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    mCurrentTouchBean.setIsTouch(true);
                    refresh();
                    return true;
                } else {
                    if (!mNeedNotScale) {
                        mAttacher.onTouch(this, event);
                    }
                    mMode = MODE_SELECT_NONE;
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mNeedNotScale = true;
                mIsMove = false;
                mDownX = event.getX();
                mDownY = event.getY();

                if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
                    //先进行变换然后判断点击区域
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    //dst用于存储变换后的点
                    float[] dst = new float[2];
                    mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});
                    RectF vr = mCurrentTouchBean.getRect();
                    RectF tr = vr;
                    float d = (float) Math.sqrt((dst[0] - vr.right) * (dst[0] - vr.right) + (dst[1] - vr.bottom) * (dst[1] - vr.bottom));

                    float deleteDistance = (float) Math.sqrt((dst[0] - vr.left) * (dst[0] - vr.left) + (dst[1] - vr.top) * (dst[1] - vr.top));

                    if (vr.contains(dst[0], dst[1])) {
                        if (d <= EditTextBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                            //					System.out.println("选中按钮");
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                            mMode = MODE_SCALE_OR_ROTATION;
                            if (vr.width() > tr.width()) {
                                mType = true;
                            } else {
                                mType = false;
                            }
                        } else if (deleteDistance <= EditTextBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                            mIsClickDelete = true;
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                        } else {
                            //					System.out.println("选中");
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                            mMode = MODE_MOVE;
                            mIsClick = true;
                        }
                        return true;
                    } else {
                        if (d <= EditTextBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                            //					System.out.println("选中按钮");
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                            mMode = MODE_SCALE_OR_ROTATION;
                            if (vr.width() > tr.width()) {
                                mType = true;
                            } else {
                                mType = false;
                            }
                        } else if (deleteDistance <= EditTextBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                            mIsClickDelete = true;
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                        } else {
                            //判断它点到的区域属于哪一个bean
                            int index = getTouchEditTextBeanIndex(mDownX, mDownY);
                            if (index != -1) {//重定位
//                                clearUnAbleText();
                                index = getTouchEditTextBeanIndex(mDownX, mDownY);
                                if (index != -1) {
                                    mSelectIndex = index;
                                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_MOVE;
                                    if (mListener != null) {
                                        mListener.onSelected(mCurrentTouchBean.getCheckId(), mCurrentTouchBean.getStyle(), mCurrentTouchBean.getFontKey());
                                    }
                                }
//							mMode = MODE_MOVE;
                            } else {//没有选中其他区域

                                if (mDrawableRect.contains(mDownX, mDownY)) {
                                    mIsNeedAddText = true;
                                    mMode = MODE_NEW_TEXT;
                                    mAttacher.onTouch(this, event);
                                    mNeedNotScale = false;
                                } else {
//								mSelectIndex = -1;
//								mCurrentTouchBean = null;
//								mHandler.removeMessages(DO_ON_DRAW);
//								mHandler.sendEmptyMessage(DO_ON_DRAW);
                                    mMode = MODE_SELECT_NONE;
                                    mAttacher.onTouch(this, event);
                                    mNeedNotScale = false;
                                }
                            }
                        }
                        return true;
                    }
                } else {//当前未选中
                    //判断它点到的区域属于哪一个bean
                    int index = getTouchEditTextBeanIndex(mDownX, mDownY);
                    if (index != -1) {
//                        clearUnAbleText();
                        index = getTouchEditTextBeanIndex(mDownX, mDownY);
                        if (index != -1) {
                            mSelectIndex = index;
                            mCurrentTouchBean = mBeans.get(mSelectIndex);
                            mCurrentTouchBean.setIsTouch(true);
                            refresh();
                            mMode = MODE_SELECT_MOVE;
                            if (mListener != null) {
                                mListener.onSelected(mCurrentTouchBean.getCheckId(), mCurrentTouchBean.getStyle(), mCurrentTouchBean.getFontKey());
                            }
                        }
                    } else {//没有选中其他区域
                        if (mDrawableRect.contains(mDownX, mDownY)) {
                            mIsNeedAddText = true;
                            mMode = MODE_NEW_TEXT;
                            mAttacher.onTouch(this, event);
                            mNeedNotScale = false;
                        } else {
//						mSelectIndex = -1;
//						mCurrentTouchBean = null;
//						mHandler.removeMessages(DO_ON_DRAW);
//						mHandler.sendEmptyMessage(DO_ON_DRAW);
                            mMode = MODE_SELECT_NONE;
                            mAttacher.onTouch(this, event);
                            mNeedNotScale = false;
                        }
                    }
                    return true;
                }
            case MotionEvent.ACTION_MOVE:
                if (mMode == MODE_SELECT_NONE || mMode == MODE_NEW_TEXT) {
                    mAttacher.onTouch(this, event);
                }
                if (mMode == MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    float newDist = spacing(event);
                    if (mIsClick && Math.abs(newDist - oldDist) <= ViewConfiguration.getTouchSlop()) {
                        return true;
                    }
                    mIsClick = false;
                    float rotation = rotation(event) - oldRotation;
                    float scale = newDist / oldDist;
                    mCurrentTouchBean.setDegree(rotation);
                    mCurrentTouchBean.setScale(scale);
                    oldRotation = rotation(event);
                    oldDist = newDist;
                    refresh();
                    return true;
                }
                float nowX = event.getX();
                float nowY = event.getY();

                float dx = nowX - mDownX;
                float dy = nowY - mDownY;
                if (mIsMove || Math.abs(dx) >= TouchUtil.OFFSET || Math.abs(dy) >= TouchUtil.OFFSET) {
                    mIsNeedAddText = false;
                    mIsClick = false;
                    mIsClickDelete = false;
                    mIsMove = true;
                    if (mMode == MODE_MOVE || mMode == MODE_SELECT_MOVE) {
                        mCurrentTouchBean.move(dx, dy);
                        mDownX = nowX;
                        mDownY = nowY;
                        refresh();
                    } else if (mMode == MODE_SCALE_OR_ROTATION) {
                        mCurrentTouchBean.dealScaleAndRotation(mDownX, mDownY, nowX, nowY);
                        mDownX = nowX;
                        mDownY = nowY;
                        refresh();
                    } else if (mMode == MODE_SELECT_NONE) {//do nothing

                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                if (mMode == MODE_SELECT_NONE) {
                    mAttacher.onTouch(this, event);
                } else if (mMode == MODE_NEW_TEXT) {
                    if (mIsNeedAddText) {
                        addText(getResources().getString(R.string.default_string), mDownX, mDownY);

                        mCurrentTouchBean = mBeans.get(mSelectIndex);
                        mCurrentTouchBean.setIsTouch(true);
                        refresh();
                    } else {
                        mAttacher.onTouch(this, event);
                    }
                }
                if (mCurrentTouchBean != null) {
                    mCurrentTouchBean.setIsTouch(false);
                }
                if (mIsClick) {//点击处理
//					System.out.println("click");
                    mIsClick = false;
                    if (mClickListener != null) {
                        mClickListener.onclick(mCurrentTouchBean);
                    }
                }
                if (mIsClickDelete) {
                    mIsClickDelete = false;
                    deleteText(mSelectIndex);
                }
                mIsMove = true;
                mMode = MODE_NONE;
                refresh();
                break;
        }
        return super.onTouchEvent(event);
    }

    // 触碰两点间距离
    private float spacing(MotionEvent event) {
        try {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return (float) Math.sqrt(x * x + y * y);
        } catch (Exception e) {
            return oldDist;
        }
    }

    // 取旋转角度
    private float rotation(MotionEvent event) {
        try {
            double delta_x = (event.getX(0) - event.getX(1));
            double delta_y = (event.getY(0) - event.getY(1));
            double radians = Math.atan2(delta_y, delta_x);
            return (float) Math.toDegrees(radians);
        } catch (Exception e) {
            return oldRotation;
        }
    }

    //用于获取正确的Rect
    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mSrcBitmap != null && !mIsInit && !mSrcBitmap.isRecycled()) {
            init(getViewRect());
        }
    }

    public void refresh() {
        if (!mHandler.hasMessages(DO_ON_DRAW)) {
            mHandler.sendEmptyMessage(DO_ON_DRAW);
        }
    }


    ///########################################

    @Override
    public void setPhotoViewRotation(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationTo(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationBy(float rotationDegree) {
        mAttacher.setRotationBy(rotationDegree);
    }

    @Override
    public boolean canZoom() {
        return mAttacher.canZoom();
    }

    @Override
    public RectF getDisplayRect() {
        return mAttacher.getDisplayRect();
    }

    @Override
    public Matrix getDisplayMatrix() {
        return mAttacher.getDrawMatrix();
    }

    @Override
    public boolean setDisplayMatrix(Matrix finalRectangle) {
        return mAttacher.setDisplayMatrix(finalRectangle);
    }

    @Override
    @Deprecated
    public float getMinScale() {
        return getMinimumScale();
    }

    @Override
    public float getMinimumScale() {
        return mAttacher.getMinimumScale();
    }

    @Override
    @Deprecated
    public float getMidScale() {
        return getMediumScale();
    }

    @Override
    public float getMediumScale() {
        return mAttacher.getMediumScale();
    }

    @Override
    @Deprecated
    public float getMaxScale() {
        return getMaximumScale();
    }

    @Override
    public float getMaximumScale() {
        return mAttacher.getMaximumScale();
    }

    @Override
    public float getScale() {
        return mAttacher.getScale();
    }

    @Override
    public ScaleType getScaleType() {
        return mAttacher.getScaleType();
    }

    @Override
    public void setAllowParentInterceptOnEdge(boolean allow) {
        mAttacher.setAllowParentInterceptOnEdge(allow);
    }

    @Override
    @Deprecated
    public void setMinScale(float minScale) {
        setMinimumScale(minScale);
    }

    @Override
    public void setMinimumScale(float minimumScale) {
        mAttacher.setMinimumScale(minimumScale);
    }

    @Override
    @Deprecated
    public void setMidScale(float midScale) {
        setMediumScale(midScale);
    }

    @Override
    public void setMediumScale(float mediumScale) {
        mAttacher.setMediumScale(mediumScale);
    }

    @Override
    @Deprecated
    public void setMaxScale(float maxScale) {
        setMaximumScale(maxScale);
    }

    @Override
    public void setMaximumScale(float maximumScale) {
        mAttacher.setMaximumScale(maximumScale);
    }


    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setOnMatrixChangeListener(CanvasPhotoViewAttacher.OnMatrixChangedListener listener) {
        mAttacher.setOnMatrixChangeListener(listener);
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
        mAttacher.setOnLongClickListener(l);
    }

    @Override
    public void setOnPhotoTapListener(CanvasPhotoViewAttacher.OnPhotoTapListener listener) {
        mAttacher.setOnPhotoTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener() {
        return mAttacher.getOnPhotoTapListener();
    }

    @Override
    public void setOnViewTapListener(CanvasPhotoViewAttacher.OnViewTapListener listener) {
        mAttacher.setOnViewTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnViewTapListener getOnViewTapListener() {
        return mAttacher.getOnViewTapListener();
    }

    @Override
    public void setScale(float scale) {
        mAttacher.setScale(scale);
    }

    @Override
    public void setScale(float scale, boolean animate) {
        mAttacher.setScale(scale, animate);
    }

    @Override
    public void setScale(float scale, float focalX, float focalY, boolean animate) {
        mAttacher.setScale(scale, focalX, focalY, animate);
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (null != mAttacher) {
            mAttacher.setScaleType(scaleType);
        }
    }

    @Override
    public void setZoomable(boolean zoomable) {
        mAttacher.setZoomable(zoomable);
    }

    @Override
    public Bitmap getVisibleRectangleBitmap() {
        return mAttacher.getVisibleRectangleBitmap();
    }

    @Override
    public void setZoomTransitionDuration(int milliseconds) {
        mAttacher.setZoomTransitionDuration(milliseconds);
    }

    @Override
    public IPhotoView getIPhotoViewImplementation() {
        return mAttacher;
    }

    @Override
    public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {
        mAttacher.setOnDoubleTapListener(newOnDoubleTapListener);
    }

    @Override
    public float getBaseScale() {
        return mAttacher.getBaseScale();
    }

    @Override
    protected void onDetachedFromWindow() {
        mAttacher.cleanup();
        super.onDetachedFromWindow();
    }

    private RectF mSupportDrawableRect;
    private RectF mBaseDrawableRect;


    /**
     * 这个方法要在Init后调用
     */
    private void countDrawableInitPosition(RectF viewRect) {
        mSupportDrawableRect = new RectF();
        float width = mSrcBitmap.getWidth();
        float height = mSrcBitmap.getHeight();

        float vW = viewRect.width();
        float vH = viewRect.height();

        float w, h;

        if (width / height > vW / vH) {//宽顶着
            w = vW;
            h = w / width * height;
        } else {//高顶着
            h = vH;
            w = h / height * width;
        }

        mSupportDrawableRect.left = (vW - w) / 2 + viewRect.left;
        mSupportDrawableRect.top = (vH - h) / 2 + viewRect.top;
        mSupportDrawableRect.right = mSupportDrawableRect.left + w;
        mSupportDrawableRect.bottom = mSupportDrawableRect.top + h;
    }

    private void countScaleAndDo() {
        int len = mBeans.size();
        for (int i = 0; i < len; i++) {
            TextBean bean = mBeans.get(i);
            bean.doScaleMove(mBaseDrawableRect, mSupportDrawableRect, getImageMatrix(), mCacheMatrix, mRect);
        }
    }

    public void statistics() {
        for (int i = 0; i < mUsedFontKey.size(); i++) {
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_FONT_BAR_APPLY,
                    StatisticsConstant.UMENG_CUSTOM_EVENT_KEY_CLICK, mUsedFontKey.get(i));
        }
    }
}
